package com.example.baselibrary.receivers

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.example.baselibrary.utlis.LogUtils

class BootReceiver : BroadcastReceiver() {

    companion object {
        private const val ACTION_DELAYED_START =
            "com.example.baselibrary.receivers.ACTION_DELAYED_START"
        // 定义延迟启动时间常量，单位为毫秒（30秒）
        private const val DELAY_START_TIME_MS = 1000 * 30L
    }

    override fun onReceive(context: Context, intent: Intent?) {
        LogUtils.logEvent("BootReceiver接收到广播，action: ${intent?.action}")

        when (intent?.action) {
            // 监听系统启动完成
            Intent.ACTION_BOOT_COMPLETED -> {
                LogUtils.logEvent("检测到系统启动完成，设置延迟启动")
                scheduleDelayedStart(context, DELAY_START_TIME_MS)
            }

            // 监听用户解锁设备（避免锁屏界面启动）
            Intent.ACTION_USER_UNLOCKED -> {
                LogUtils.logEvent("检测到用户解锁设备，立即启动应用")
                startApp(context)
            }

            ACTION_DELAYED_START -> {
                LogUtils.logEvent("接收到延迟启动广播，开始启动应用")
                startApp(context)
            }

            else -> {
                LogUtils.logEvent("未处理的广播action: ${intent?.action}")
            }
        }
    }

    private fun scheduleDelayedStart(context: Context, delayMillis: Long) {
        LogUtils.logEvent("开始设置延迟启动任务，延迟时间: ${delayMillis}毫秒")

        val intent = Intent(context, BootReceiver::class.java).apply {
            action = ACTION_DELAYED_START
        }

        val pendingIntent = PendingIntent.getBroadcast(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val triggerTime = System.currentTimeMillis() + delayMillis

        LogUtils.logEvent("计算触发时间: $triggerTime")

        // 使用 setExact 确保精确的时间触发
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP,
                triggerTime,
                pendingIntent
            )
            LogUtils.logEvent("使用setExactAndAllowWhileIdle设置精确闹钟")
        } else {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent)
            LogUtils.logEvent("使用setExact设置精确闹钟")
        }

        LogUtils.logEvent("延迟启动任务设置完成")
    }

    private fun startApp(context: Context) {
        LogUtils.logEvent("开始启动应用程序")

        val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }

        if (launchIntent == null) {
            LogUtils.logEvent("获取应用程序启动Intent失败，包名: ${context.packageName}")
            return
        }

        try {
            context.startActivity(launchIntent)
            LogUtils.logEvent("应用程序启动成功")
        } catch (e: Exception) {
            LogUtils.logEvent("启动应用程序时发生异常: ${e.message}")
        }
    }
}
